import { PlusOutlined, QuestionCircleOutlined } from '@ant-design/icons';
import { Button, Divider, message, Input, Select, Modal } from 'antd';
import React, { useState, useRef } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import ProTable, { ProColumns, ActionType } from '@ant-design/pro-table';
import FirstOrgListComponent from '../System/components/FirstOrgListComponent';
import AddOrgOrderForm from './components/AddOrgOrderForm';
import { OrgOrderListItem } from './data.d';
import { orgOrderList,addOrgOrder, updateOrgOrder, orgOrderDel } from './service';

const ServerList: React.FC<{}> = () => {
  const [createModalVisible, handleModalVisible] = useState<boolean>(false);
  const [formValues, setFormValues] = useState<OrgOrderListItem>({});
  const [deleteModalVisible, handleDeleteModalVisible] = useState<boolean>(false);
  const actionRef = useRef<ActionType>();

  //添加
  const addComment = (orgOrder: OrgOrderListItem) => {
    new Promise((resolve, reject) => {
      addOrgOrder(orgOrder)
        .then((res) => {
          if(res){
            if (res.code === 200) {
              const hide = message.success('添加成功');
              handleModalVisible(false);
              if (actionRef.current) {
                hide();
                actionRef.current.reload();
              }
              resolve(true);
            }else {
              message.error('添加失败'+res.message);
              resolve(false);
            }
          }else {
            message.error('添加失败');
            resolve(false);
          }
        })
        .catch((error) => {
          message.error('请求失败');
          reject(error);
        });
    });
  };

  //编辑
  const updateComment = (orgOrder: OrgOrderListItem) => {
    new Promise((resolve, reject) => {
      updateOrgOrder(orgOrder)
        .then((res) => {
          if(res){
            if (res.code === 200) {
              const hide = message.success('保存成功');
              handleModalVisible(false);
              if (actionRef.current) {
                hide();
                actionRef.current.reload();
              }
              resolve(true);
            }else {
              message.error('保存失败，'+res.message);
              resolve(false);
            }
          }else {
            message.error('保存失败');
            resolve(false);
          }
        })
        .catch((error) => {
          message.error('请求失败');
          reject(error);
        });
    });
  };

  //【新建/编辑】对话框，确定按钮点击
  const handleUpdate = async (values: OrgOrderListItem) => {
    if (values) {
      if (values.id) {
        //编辑服务
        updateComment(values);
      } else {
        //添加服务
        addComment(values);
      }
    }
  };

  //删除--删除弹出框
  const delConfirm = (id: number) => {
    Modal.confirm({
      visible: deleteModalVisible,
      title: '确定删除',
      icon: <QuestionCircleOutlined />,
      content: '此记录将永久删除',
      okText: '确认',
      cancelText: '取消',
      onOk: () => {
        return new Promise((resolve, reject) => {
          orgOrderDel(id)
            .then((res) => {
              if (res.code === 200) {
                message.success('删除成功');
                handleDeleteModalVisible(false);
                actionRef.current?.reload?.();
                resolve(true);
              } else {
                message.error('删除失败');
                resolve(false);
              }
            })
            .catch((error) => {
              message.error('删除失败');
              reject(error);
            });
        });
      },
    });
  };

  const columns: ProColumns<OrgOrderListItem>[] = [
    {
      title: '序号',
      dataIndex: 'index',
      valueType: 'text',
      hideInSearch: true, 
    },
    {
      title: '所属机构',
      dataIndex: 'topOrgId',
      hideInTable: true,
      renderFormItem: (_, { type, defaultRender, ...rest }, form) => {
        if (type === 'form') {
          return null;
        }
        const status = form.getFieldValue('state');
        if (status !== 'open') {
          return (
            <FirstOrgListComponent 
              disabled={false} 
              defaultvalue={null} 
              selectChange={(value) => {
                form.setFieldsValue({topOrgId:value});
                form.submit();
              }}>
            </FirstOrgListComponent>
          );
        }
        return defaultRender(_);
      },
      valueType: 'text',
    },
    {
      title: '所属机构',
      dataIndex: 'topOrgName',
      valueType: 'text',
      hideInSearch: true, 
    },
    {
      title: '最大设备数',
      dataIndex: 'totalNum',
      valueType: 'text',
      hideInSearch: true, 
    },
    {
      title: '当前设备数',
      dataIndex: 'currentNum',
      valueType: 'text',
      hideInSearch: true, 
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => (
        <>
          <a
          onClick={() => {
            handleModalVisible(true);
            setFormValues(record);
          }}
        >
          编辑
        </a>
        <Divider type="vertical" />
          <a
             onClick={() => {
              delConfirm(record.id);
            }}
          >删除</a>
        </>
      ),
    },
  ];

  return (
    <PageContainer>
      <ProTable<OrgOrderListItem>
        options={false}
        actionRef={actionRef}
        rowKey="key"
        pagination={{ showQuickJumper: true,defaultPageSize: 10 }}
        toolBarRender={() => [
          <Button type="primary" onClick={() => {handleModalVisible(true);setFormValues({})}}>
            <PlusOutlined /> 添加服务
          </Button>,
        ]}
        request={(params, sorter, filter) => orgOrderList({ ...params, sorter, filter })}
        columns={columns}
      />
      <AddOrgOrderForm
        onSubmit={handleUpdate}
        onCancel={() => handleModalVisible(false)} 
        modalVisible={createModalVisible}
        values={formValues}
      >
        <ProTable<OrgOrderListItem, OrgOrderListItem> />
      </AddOrgOrderForm>
    </PageContainer>
  );
};

export default ServerList;
